package model

import (
	"fmt"
	"gorm.io/gorm"
	"time"
)

const (
	Exercise_Name = "exercise"
	Creat_At      = "create_at"
)

type Exercise struct {
	Id       uint      `json:"id"`
	Calorie  float64   `json:"calorie"`
	UserId   uint      `json:"user_id"`
	CreateAt time.Time `json:"create_at"`
}

func (Exercise) TableName() string {
	return Exercise_Name
}

func (e *Exercise) Save(db *gorm.DB) error {
	return db.Save(e).Error
}

func (e *Exercise) Delete(db *gorm.DB) error {
	return db.Delete(e).Error
}

func (e *Exercise) Updates(db *gorm.DB) error {
	return db.Updates(e).Error
}

func (e *Exercise) Get(db *gorm.DB) error {
	return db.First(e).Error
}

type ExerciseSelectConditions struct {
	Start Time `json:"start"`
	End   Time `json:"end"`
}

func ListExercise(db *gorm.DB, where map[string]any, conditions *ExerciseSelectConditions) []Exercise {
	var exercise []Exercise
	sql := db.Table(Exercise_Name).Where(where)

	if conditions.Start.Time.Unix() > 0 {
		sql = sql.Where(GtEq(Creat_At, conditions.Start.Time))
	}
	if conditions.End.Time.Unix() > 0 {
		sql = sql.Where(LtEq(Creat_At, conditions.End.Time))
	}
	sql.Find(&exercise)
	return exercise
}

func GetTotalCalorie(db *gorm.DB, start time.Time, end time.Time, userId uint) float64 {
	var total float64
	_ = db.Raw("select sum(calorie) from exercise where user_id = ? and create_at > ? and create_at < ?", userId, start, end).Scan(&total).Error
	return total
}

func GetDataDaysCount(db *gorm.DB, start time.Time, end time.Time, userId uint) uint {
	var total uint
	sql := fmt.Sprintf("select year(%s) as y, month(%s) as m, day(%s) as d from %s where user_id = ? and %s > ? and %s < ?", Creat_At, Creat_At, Creat_At, Exercise_Name, Creat_At, Creat_At)
	sql = fmt.Sprintf("select count(distinct y, m, d) from (%s) as temp", sql)
	_ = db.Raw(sql, userId, start, end).Scan(&total).Error
	return total
}
